<template>
  <dir>
    <div>
      <div class="my-flex">
        <el-input
          placeholder="根据用户名搜索"
          v-model="user.username"
          clearable
          style="width: 20%; margin-right: 1%"
        >
        </el-input>
        <el-input
          placeholder="根据电话号码搜索"
          v-model="user.phonenumber"
          clearable
          style="width: 20%; margin-right: 1%"
        >
        </el-input>
        <el-button icon="el-icon-search" circle @click="searchUser"></el-button>
        <el-button icon="el-icon-delete" circle @click="user = {}"></el-button>
      </div>
      <div class="my-flex">
        <el-table :data="userList" style="width: 100%">
          <el-table-column type="index" width="50" label="序号">
            <template slot-scope="scope">
              {{ (pageIndex - 1) * pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="avatar" label="头像" width="100">
            <template slot-scope="scope">
              <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.avatar"
                fit="fill"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户名" width="150">
          </el-table-column>
          <el-table-column prop="password" label="密码" width="150">
          </el-table-column>
          <el-table-column prop="phonenumber" label="电话" width="150">
          </el-table-column>
          <el-table-column prop="createtime" label="创建时间" width="90">
          </el-table-column>
          <el-table-column
            prop="lastlogintime"
            label="上一次登录时间"
            width="90"
          >
          </el-table-column>
          <el-table-column prop="updatetime" label="更新时间" width="90">
          </el-table-column>
          <el-table-column prop="userstatus" label="状态" width="140">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.userstatus"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="启用"
                inactive-text="禁用"
                :active-value="1"
                :inactive-value="0"
                @change="changeUserStatus(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="userrole" label="角色" width="120">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.userrole"
                placeholder="请选择"
                @change="changeUserRole(scope.row)"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>

          <el-table-column prop="remark" label="备注"> </el-table-column>

          <el-table-column label="操作">
            <template slot-scope="scope">
              <div class="my-flex">
                <el-button
                  type="warning"
                  @click="openDialog(scope.row)"
                  style="margin-right: 10px"
                  >修改</el-button
                >
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="是否删除该用户？"
                  @confirm="deleteUserById(scope.row)"
                >
                  <el-button slot="reference" type="danger">删除</el-button>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="my-flex">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageIndex"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog title="修改用户信息" :visible.sync="dialogVisible" width="30%">
      <el-form label-position="left" label-width="80px" :model="row">
        <el-form-item label="头像">
          <el-image
            style="width: 100px; height: 100px"
            :src="row.avatar"
            fit="fill"
          ></el-image>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="row.username" :readonly="true"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="row.password"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="row.phonenumber" :readonly="true"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="row.userstatus"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="启用"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="row.userrole" placeholder="请选择">
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="row.remark"></el-input>
        </el-form-item>
        <el-form-item label="操作">
          <div class="my-flex">
            <el-button type="primary" @click="updateUserById">确定</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </dir>
</template>


<script>
export default {
  created() {
    this.getUserListByConditions();
    this.getTotalUserCount();
  },
  data() {
    return {
      dialogVisible: false, //打开关闭对话框
      userList: [], //用户列表
      row: {}, //选中的行
      roleOptions: [
        { label: "普通用户", value: 1 },
        { label: "咨询师", value: 2 },
        { label: "管理员", value: 3 },
      ],
      user: {
        username: "",
        phonenumber: "",
      },
      pageIndex: 1, //页数
      pageSize: 5, //页大小
      total: 0, //总条数
    };
  },
  methods: {
    //改变用户状态
    changeUserStatus(row) {
      let userid = row.userid;
      let userstatus = row.userstatus;
      //发送请求改变用户状态
      this.$request.postHttp({
        url: "/user/changeUserStatusById",
        params: { userid: userid, userstatus: userstatus },
        success: (data) => {
          console.log(data);
          if (data.code == 200) {
            this.$message({
              message: data.msg,
              type: "success",
            });
            this.getUserListByConditions(this.user);
            this.getTotalUserCount();
          }
        },
        error: (error) => {},
      });
    },
    //改变用户角色
    changeUserRole(row) {
      let userid = row.userid;
      let userrole = row.userrole;
      //发送请求改变用户角色
      this.$request.postHttp({
        url: "/user/changeUserRoleById",
        params: { userid: userid, userrole: userrole },
        success: (data) => {
          console.log(data);
          if (data.code == 200) {
            this.$message({
              message: data.msg,
              type: "success",
            });
            this.getUserListByConditions(this.user);
            this.getTotalUserCount();
          }
        },
        error: (error) => {},
      });
    },
    //获取用户头像的链接
    getImageUrl(avatar) {
      let url = this.$store.getters.getIpAddr + "/" + avatar;
      return url; // 假设 this.baseUrl 是在组件中定义的基础 URL
    },
    //根据条件获取用户列表
    getUserListByConditions(user) {
      if (user == null) {
        user = {};
      }
      user.pageIndex = this.pageIndex;
      user.pageSize = this.pageSize;
      this.$request.postHttp({
        url: "/user/getUserListByConditions",
        data: user,
        success: (data) => {
          console.log(data);
          if (data.code == 200) {
            this.userList = this.handleUserList(data.userList);
            this.getTotalUserCount();
          }
        },
        error: (error) => {},
      });
    },
    //获取总条数
    getTotalUserCount() {
      this.$request.postHttp({
        url: "/user/getTotalUserCount",
        data: this.user,
        success: (data) => {
          if (data.code == 200) {
            this.total = data.count;
          }
        },
        error: (error) => {},
      });
    },
    //查找用户
    searchUser() {
      this.getUserListByConditions(this.user);
    },
    //页面大小变化
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getUserListByConditions(this.user);
      this.getTotalUserCount();
    },
    //当前页变化
    handleCurrentChange(pageIndex) {
      this.pageIndex = pageIndex;
      this.getUserListByConditions(this.user);
      this.getTotalUserCount();
    },
    //处理userList
    handleUserList(userList) {
      // 使用 map 方法遍历用户列表并执行操作
      const modifiedUserList = userList.map((user) => {
        console.log(user.username);
        // 在这里可以对用户对象进行修改或其他操作
        user.avatar = this.$store.getters.getIpAddr + "/" + user.avatar;
        user.createtime = this.formattedDate(user.createtime);
        user.updatetime = this.formattedDate(user.updatetime);
        user.lastlogintime = this.formattedDate(user.lastlogintime);
        return user;
      });
      return modifiedUserList;
    },
    //格式化日期
    formattedDate(originalDate) {
      // 创建 Date 对象
      const date = new Date(originalDate);

      // 使用 Date 对象的方法获取年、月、日、小时、分钟和秒
      const year = date.getFullYear();
      const month = ("0" + (date.getMonth() + 1)).slice(-2);
      const day = ("0" + date.getDate()).slice(-2);
      const hours = ("0" + date.getHours()).slice(-2);
      const minutes = ("0" + date.getMinutes()).slice(-2);
      const seconds = ("0" + date.getSeconds()).slice(-2);

      // 将获取到的年月日时分秒拼接成指定格式的字符串
      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

      return formattedDate;
    },
    //打开修改对话框
    openDialog(row) {
      this.dialogVisible = true;
      this.row = row;
    },
    //根据id更新用户
    updateUserById() {
      delete this.row.avatar;
      delete this.row.createtime;
      delete this.row.lastlogintime;
      this.row.updatetime = new Date();
      this.$request.postHttp({
        url: "/user/updateUserByUserId",
        data: this.row,
        success: (data) => {
          if (data.code == 200) {
            this.$message({
              message: "修改成功！",
              type: "success",
            });
            this.dialogVisible = false;
            this.getUserListByConditions(this.user);
            this.getTotalUserCount();
          }
        },
        error: (error) => {},
      });
    },
    //根据id删除用户
    deleteUserById(row) {
      this.row = row;
      delete this.row.createtime;
      delete this.row.lastlogintime;
      delete this.row.updatetime;
      this.$request.postHttp({
        url: "/user/deleteUserById",
        data: this.row,
        success: (data) => {
          if (data.code == 200) {
            this.$message({
              message: data.msg,
              type: "success",
            });
            this.getUserListByConditions(this.user);
            this.getTotalUserCount();
          } else {
            this.$message({
              message: "删除失败！",
              type: "error",
            });
          }
        },
        error: (error) => {},
      });
    },
  },
};
</script>


<style scoped>
.my-flex {
  display: flex;
  align-items: center;
}
</style>